from django.http import JsonResponse
from django.views.generic import View
from django.contrib.contenttypes.models import ContentType
from ..models.Publications import Publication

class PubTypeView(View):
     def get(self, request):
        res = {"code": 400, "message": "", "data": None}
        try:
            pub_content_type = ContentType.objects.get_for_model(Publication)
            pub_subclasses = ContentType.objects.filter(app_label=pub_content_type.app_label).exclude(id=pub_content_type.id)

            subclass_info = []
            for subclass in pub_subclasses:
                model_class = subclass.model_class()
                if issubclass(model_class, Publication):
                    subclass_info.append({
                        'uuid':  model_class.__name__,
                        'display_str': model_class._meta.verbose_name + '(' + model_class.__name__ + ')',
                        'name': model_class.__name__,
                        'zh_name': model_class._meta.verbose_name,
                    })
            subclass_info.append({
                'uuid': 'unknown',
                'display_str': '未知(unknown)',
                'name': 'unknown',
                'zh_name': '未知',
            })
            # liter_type = LiteratureType.objects.all().order_by('create_date')
            # total_count = liter_type.count()
            res_data = {}
            res_data["total_count"] = len(subclass_info)
            # liter_type_list_serializer = LiterTypeListSerializer(
            #     liter_type, many=True)
            res_data["options"] = subclass_info
            res["code"] = 200
            res["message"] = "查询成功"
            res["data"] = res_data
            # print(res_data)
            return JsonResponse(res)
        except Exception as e:
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
        return JsonResponse(res)